import type { RouteRecordRaw } from "vue-router";
import type { App } from "vue";
import { createRouter, createWebHashHistory } from "vue-router";
import Cookies from "js-cookie";
import { useUserStoreWithOut } from "@/store/modules/user";
import * as http from "@/request/http";

const userStore = useUserStoreWithOut();

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/index.vue"),
  },
  // {
  //   path: "/homepage",
  //   name: "homepage",
  //   component: () => import("../views/homepage/homepage.vue"),
  //   children: [],
  // },
  // {
  //   path: "/pms",
  //   component: () => import("../views/homepage/homepage.vue"),
  //   children: [
  //     {
  //       path: "product",
  //       component: () => import("../views/pms/product.vue"),
  //     },
  //     {
  //       path: "addProduct",
  //       component: () => import("../views/pms/addProduct.vue"),
  //     },
  //   ],
  // },
];

const router = createRouter({
  history: createWebHashHistory(), //模式mode
  routes,
});

//路由守卫 解决刷新空白页情况
router.beforeEach(async (to, from, next) => {
  //token 存在 && pinia 没有 menus (重新获取用户信息)
  const token = Cookies.get("token");
  const menus = userStore.menus;
  console.log(token, menus);
  //当存在token 并且 菜单数组是0的情况下
  if (token && menus.length === 0) {
    //重新获取用户信息
    let adminData = await http.admin.getAdminInfo();
    if (adminData.code === 200) {
      //存储到pinia
      userStore.updateMenus(adminData.data.menus);
      //获取getters
      const newMenus = userStore.getMenusConf;
      //遍历对象 得到遍历后对象的所有值
      for (let key in newMenus) {
        let routerObj: RouteRecordRaw = {
          path: "/" + newMenus[key].name,
          name: newMenus[key].name,
          component: () => import("../views/homepage/homepage.vue"),
          children: [],
        };
        //遍历新对象的子路由,得到相对应的新对象及子路由
        newMenus[key].children?.forEach((submenu) => {
          routerObj.children!.push({
            path: submenu.name,
            name: submenu.name,
            component: () =>
              import(`@/views/${newMenus[key].name}/${submenu.name}.vue`),
          });
        });
        console.log(routerObj);
        router.addRoute(routerObj);
      }
      router.addRoute({
        path: "/",
        name: "home",
        redirect: "/index",
        component: () => import("@/views/homepage/homepage.vue"),
        children: [
          {
            path: "/index",
            name: "index",
            component: () => import("@/views/index/index.vue"),
          },
        ],
      });
      //生成路由规则
      return next(to);
    } else {
      //删除token,跳转到登录页
      Cookies.remove("token");
      return next("/login");
    }
    // token 不存在且不是去登录页就跳转登录页
  } else if (!token && to.path !== "/login") {
    return next("/login");
  } else if (token && to.path === "/login") {
    return next(from);
  } else {
    next();
  }
});

//初始化方法
export const initRouter = (app: App<Element>) => {
  app.use(router);
};

export default router;
